package com.knowswift.issues.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowswift.common.bean.issue.po.MonitorRecord;
import com.knowswift.common.bean.issue.vo.MonitorAlertCountParam;
import com.knowswift.common.bean.issue.vo.MonitorAlertCountVO;
import com.knowswift.common.bean.issue.vo.MonitorRecordParam;
import com.knowswift.common.bean.project.vo.ModulePermissionVO;
import com.knowswift.common.bean.project.vo.ProjectLimit;
import com.knowswift.common.common.GlobalProperty;
import com.knowswift.common.common.Page;
import com.knowswift.common.exception.CustomFailureException;
import com.knowswift.common.utils.WrappedBeanCopier;
import com.knowswift.issues.mapper.MonitorRecordMapper;
import com.knowswift.security.account.User;
import com.knowswift.security.account.UserService;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MonitorRecordService extends ServiceImpl<MonitorRecordMapper, MonitorRecord> {

    @Resource
    private ModulePermissionService modulePermissionService;

    public Object alertCount(MonitorAlertCountParam param, List<String> moduleProjects) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startDate = param.getStartDate();
        String endDate = param.getEndDate();

        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            throw new CustomFailureException("开始时间和结束时间不能为空");
        }

        LocalDateTime startDateTime;
        LocalDateTime endDateTime;

        if ("year".equals(param.getCountInterval())) {
            try {
                LocalDateTime.parse(startDate + "-01-01 00:00:00", formatter);
                LocalDateTime.parse(endDate + "-01-01 00:00:00", formatter);
            } catch (Exception e) {
                throw new CustomFailureException("时间参数错误");
            }

            List<MonitorAlertCountVO> monitorAlertCountVOS = baseMapper.alertCountByYear(param, moduleProjects);

            return monitorAlertCountVOS.stream().collect(Collectors.groupingBy(MonitorAlertCountVO::getDate));
        } else if ("month".equals(param.getCountInterval())) {
            try {
                startDateTime = LocalDateTime.parse(startDate + "-01 00:00:00", formatter);
                endDateTime = LocalDateTime.parse(endDate + "-01 00:00:00", formatter);
            } catch (Exception e) {
                throw new CustomFailureException("时间参数错误");
            }

//            long monthsBetween = ChronoUnit.MONTHS.between(startDateTime, endDateTime);
//            if (monthsBetween > 12 || monthsBetween < 0) {
//                throw new CustomFailureException("开始时间与结束时间不能超过12月，并且开始时间不能超过结束时间");
//            }

            return baseMapper.alertCountByMonth(param, moduleProjects);
        } else if ("day".equals(param.getCountInterval())) {
            try {
                startDateTime = LocalDateTime.parse(startDate + " 00:00:00", formatter);
                endDateTime = LocalDateTime.parse(endDate + " 00:00:00", formatter);
            } catch (Exception e) {
                throw new CustomFailureException("时间参数错误");
            }

//            long monthsBetween = ChronoUnit.MONTHS.between(startDateTime, endDateTime);
//            if (monthsBetween >= 36) {
//            }

            return baseMapper.alertCountByDay(param, moduleProjects);
        }
        else {
            throw new CustomFailureException("时间间隔参数错误");
        }

    }

    public Page<MonitorRecord> getMonitorRecordPage(MonitorRecordParam condition, List<String> moduleProjects, Page<MonitorRecord> page) {
        return baseMapper.getMonitorRecordPage(condition.getStartDate(), condition.getEndDate(), GlobalProperty.DEVICE_STATUS_ALERT, condition.getDeviceId(), moduleProjects, page);
    }

    public List<String> getModuleProjects(User user) {
        List<String> strings = null;
        boolean allIssues = UserService.checkAuthority(user, "allIssues");
        //boolean ownIssues = UserService.checkAuthority(user, "ownIssues");//TODO 是否匹配这个权限，装置的权限和用户上报无关
        boolean projectIssues = UserService.checkAuthority(user, "projectIssues");

//        if (!allIssues && !ownIssues && projectIssues) {
        if (!allIssues && projectIssues) {
            strings = new ArrayList<>();
            List<ModulePermissionVO> permissions = modulePermissionService.getBaseMapper().getByUserId(user.getUserId());
            for (ModulePermissionVO permission : permissions) {
                List<ProjectLimit> projectLimits = WrappedBeanCopier.JSONArrayToList(permission.getProjects(), ProjectLimit.class);
                for (ProjectLimit projectLimit : projectLimits) {
                    if (BooleanUtils.isTrue(projectLimit.getLimit())) {
                        strings.add(permission.getModuleName() + projectLimit.getProjectName());
                    }
                }
            }
        }

        return strings;
    }

}
